package main

import "fmt"

func main() {

	ch := make(chan int, 3)

	safeOutData(ch)
	safeOutData(ch)
	safeOutData(ch)

	safeInData(ch, 1)
	safeInData(ch, 2)

	close(ch)
	safeOutData(ch)
	safeOutData(ch)
	safeOutData(ch)

	//ch <- 1 // panic: send on closed channel
	safeInData(ch, 99)
	safeInData(ch, 88)
}

func safeOutData(ch chan int) {
	select {
	case val, ok := <-ch:
		if ok {
			fmt.Printf("读取到数据: %d\n", val)
		} else {
			fmt.Println("通道已关闭")
		}
	default:
		fmt.Println("管道数据为空")
	}

}

func safeInData(ch chan int, data int) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("通道已关闭或发生其他异常,写入数据失败", data, r)
		}
	}()

	select {
	case ch <- data:
		fmt.Println("成功写入数据", data)
	default:
		fmt.Println("通道已满, 无法写入数据")
	}
}
